<?php

namespace Model;

use Core\Db\Feature\InjectMetaFieldFeature;
use Core\Db\Feature\LightMetaFeature;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\Feature\FeatureSet;
use Zend\Db\TableGateway\Feature\MetadataFeature;
use Zend\Db\TableGateway\TableGateway;
use Zend\ServiceManager\AbstractFactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class GenericTableFactory implements AbstractFactoryInterface{

    /**
     * Determine if we can create a service with name
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @param $name
     * @param $requestedName
     * @return bool
     */
    public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
    {
        if (class_exists($requestedName) && class_exists(substr($requestedName,0, strlen($requestedName)-5))){
            return true;
        }

        return false;
    }

    /**
     * Create service with name
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @param $name
     * @param $requestedName
     * @return mixed
     */
    public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
    {
//        $tableName = substr($name, strlen('module') - 1, strlen($name) - strlen('module') - strlen('table') + 1);
        $tmpArr = explode('\\',$requestedName);
        $tmpStr = end($tmpArr);
        $tableName = substr($tmpStr,0, strlen($tmpStr) - strlen('Table'));

        $tableName = $this->fromCamelCase($tableName);

        $entityClassName =  substr($requestedName,0, strlen($requestedName)-5);
        $entityClass = new $entityClassName;
        $class = $requestedName;
        $myInstance = new $class;
        $dbAdapter = $serviceLocator->get('Zend\Db\Adapter\Adapter');

        $resultSetPrototype = new ResultSet();
        $resultSetPrototype->setArrayObjectPrototype($entityClass);
        $featureSet = new FeatureSet();
        $featureSet->addFeature(new LightMetaFeature());
        $featureSet->addFeature(new InjectMetaFieldFeature());
//        $featureSet->addFeature(new MetadataFeature());
        $tableGateway = new TableGateway($tableName, $dbAdapter, $featureSet, $resultSetPrototype);
        $myInstance->setTableGateway($tableGateway);
        return $myInstance;
    }



    private function fromCamelCase($input) {
        preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches);
        $ret = $matches[0];
        foreach ($ret as &$match) {
            $match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match);
        }
        return implode('_', $ret);
    }


}

